// apis/uni-fetch.js
import { storeToRefs } from 'pinia';
// 导入安装好的 uni-app-fetch 模块
// 这个地方怎么玩
import { createUniFetch } from 'uni-app-fetch';
import { useUserStore } from '@/store/user';
let baseURL = '';
// #ifdef MP-WEIXIN || MP-ALIPAY
const wxaccountInfo = uni.getAccountInfoSync();

var wxenvVersion = wxaccountInfo.miniProgram.envVersion;
console.log(wxenvVersion, 'wxenvVersionwxenvVersion');
switch (wxenvVersion) {
	case 'develop': //开发版
		baseURL = 'https://api-test.zzqz2024.com';
		// baseURL = "https://api.zzqz2024.com";
		break;
	case 'trial': //体验版
		baseURL = 'https://api-test.zzqz2024.com';
		break;
	case 'release': //正式版
		baseURL = 'https://api.zzqz2024.com';
		break;
	default:
		baseURL = 'https://api-test.zzqz2024.com';
		break;
}
// #endif

/*  h5 的环境判断    */
// 配置符合自身业务的请求对象
const ongoingRequests = new Map();
export const uniFetch = createUniFetch({
	loading: { title: '正在加载...' },
	// baseURL: 'https://api.zzqz2024.com', // 生产环境
	// baseURL: 'http://192.168.0.129:8080', // 潘宇
	// baseURL: 'http://192.168.0.114:8080', // 王海华

	baseURL: baseURL ? baseURL : 'https://api-test.zzqz2024.com', // 测试环境
	intercept: {
		// 请求拦截器
		request(options) {
			const userState = useUserStore();
			console.log(userState.userInfo.token, '55');
			// 全局公共头信息

			const arr =
				'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoiMTUzNTI2Iiwic291cmNlVHlwZSI6IjIiLCJpc3MiOiJxYl90ZWNoIiwibW9iaWxlIjoiMTgxODg0MzQ2MTUiLCJleHAiOjE3MzUxMTQ5NTE4NTEsImlhdCI6MTczNTEwNDg3MTg1MSwia2V5IjoiYzBiMzZiMTFiYTFiYjM2YWY4YTA0YjZkMWYzNzYyNDAiLCJ1c2VybmFtZSI6IjE1MzUyNiJ9.saKUtnEF2uxcfRgb5yDtUMZruaikGjiFwSng_k0g4cPkoZ-YzEGxXUFBFBkfXmZWqgbVCf-FmyZKGrmH91kzqA';
			const defaultHeaders = {
				// Authorization: userState.token,
				Authorization: `Bearer ${userState.userInfo.token}`
				// Authorization: `Bearer ${arr}`
			};
			// 自定义头信息（token）
			options.header = Object.assign({}, defaultHeaders, options.header, );
			// 后续补充实际逻辑
			return options;
		},
		// 响应拦截器
		response({
			statusCode,
			data,
			config
		}) {
			// 后续补充实际逻辑
			console.log(statusCode == 401, data, baseURL, '1==========》》》》》》》》');
			if (statusCode == 401) {
				// 登录过期 重新登录 清楚数据
				uni.navigateTo({ url: '/pages/login/login' });
				return uni.utils.toast('登录已过期！请重新登录');
			}

			return data;
		},
		error(error) {
			console.log(error, 'error=========》》》');
			throw error;
		},
	},
});